package com.his.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


/**
 * <pre>
 * 这个filter负责拦截请求、
 * 获取header中的Authorization字段中的jwt，
 * 并用它进行身份认证过程
 * </pre>
 */
public class JwtFilter extends AccessControlFilter {

    /**
     * 跨域放行 获取前台请求头Authorization发过来的token数据
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        //转换成HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //有问题的话在这里debug
        String method = httpServletRequest.getMethod();
        if (method.equals("OPTIONS")) {
            return true;
        }


        //从request中获取Authorization
        String header = httpServletRequest.getHeader("Authorization");
        if (header == null || header.isEmpty()) {
            return false;
        }
        //截取Authorization信息用空格隔开
        String[] strings = header.split(" ", 2);
        if (strings.length != 2 || !strings[0].equals("Bearer")) {
            return false;
        }

        //取出第二段jwt字符串
        String jwt = strings[1];
        if (!JwtUtils.verify(jwt)) {
            return false;
        }
        Subject subject = SecurityUtils.getSubject();
        subject.login(new JwtToken(jwt));
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        return false;
    }
}
